<!-- 线 -->
<template>
  <div @click.stop="yourLocalHandler" :class="[containerLineSeries]" :style="{ width: parsedWidth, height: parsedHeight }"></div>
</template>

<script setup>
import { createChart, LineSeries } from 'lightweight-charts';
import { nextTick, onMounted, onUnmounted, ref, watch, watchEffect } from 'vue';

let chartLineSeries = null;
let lineSeries = null;
let resizeObserver = null;

// 接收数据
const props = defineProps({
  containerLineSeries: {
    type: String
  },
  // 宽
  width: {
    type: [String, Number],
    default: '100%'
  },
  // 高
  height: {
    type: [String, Number],
    default: '100%'
  },
  // 背景颜色
  bgColor: {
    type: String
  },
  content: Array,
  lineColor: {  // 线条颜色
    type: String,
  },
})

// 解析后的尺寸
const parsedWidth = ref('100%');
const parsedHeight = ref('100%');

// 定义配置
let chartLineSeriesOptions = {
  // 禁用坐标轴缩放
  xAxis: { scale: false },
  yAxis: { scale: false },
  // 栅格
  grid: {
    vertLines: { visible: false },
    horzLines: { visible: false },
  },
  // 十字线
  crosshair: {
    vertLine: {
      visible: false,
    },
    horzLine: {
      visible: false,
    }
  },
  // 时间轴
  timeScale: {
    visible: false,      // 完全隐藏时间轴
    borderVisible: false // 同时隐藏边框
  },
  // 价格轴
  rightPriceScale: {
    visible: false,      // 隐藏右侧价格轴
    borderVisible: false // 隐藏边框
  },
  handleScroll: false,  // 禁用鼠标滚轮缩放
  handleScale: false,   // 禁用缩放手势
  kineticScroll: false, // 禁用惯性滚动

  layout: {
    textColor: 'black',
    background: {
      color: 'transparent' // 修改为透明
    }
  },
  attributionLogo: false,
};

// 解析尺寸值的辅助函数
const parseDimension = (dimension) => {
  if (typeof dimension === 'number') {
    return dimension + 'px';
  }
  
  if (typeof dimension === 'string') {
    // 如果是百分比，返回原始值
    if (dimension.endsWith('%') || dimension.endsWith('vw') || dimension.endsWith('vh') || dimension.endsWith('rpx')) {
      return dimension;
    }
    
    // 如果是纯数字字符串，转换为像素值
    if (/^\d+$/.test(dimension)) {
      return parseInt(dimension, 10) + 'px';
    }
    
    // 如果包含单位（px, rem, em等），返回原始值
    if (/^\d+\.?\d*[a-zA-Z]+$/.test(dimension)) {
      return dimension;
    }
  }
  
  // 默认返回 100%
  return '100%';
}

// 转换 rpx 为 px (uni-app 特有)
const convertRpxToPx = (value) => {
  if (typeof value === 'string' && value.endsWith('rpx')) {
    const rpxValue = parseFloat(value);
    // 获取设备像素比
    const deviceRatio = uni.getSystemInfoSync().windowWidth / 750;
    return (rpxValue * deviceRatio) + 'px';
  }
  return value;
}

// 初始化k线图
const initSeries = () => {
  const container = document.querySelector('.' + props.containerLineSeries);
  if (!container) {
    console.warn('Container not found:', props.containerLineSeries);
    return;
  }
  if (!props.lineColor) return;
  
  // 解析并转换尺寸
  parsedWidth.value = convertRpxToPx(parseDimension(props.width));
  parsedHeight.value = convertRpxToPx(parseDimension(props.height));
  
  // 确保容器有尺寸
  container.style.width = parsedWidth.value;
  container.style.height = parsedHeight.value;
  
  // 延迟一小段时间确保DOM渲染完成
  setTimeout(() => {
    const computedWidth = container.clientWidth || 200;
    const computedHeight = container.clientHeight || 100;
    
    // 更新配置
    chartLineSeriesOptions.width = computedWidth;
    chartLineSeriesOptions.height = computedHeight;
    
    try {
      chartLineSeries = createChart(container, chartLineSeriesOptions);
      lineSeries = chartLineSeries.addSeries(LineSeries, {
        color: props.lineColor,
        lineWidth: 2,         // 线条宽度
        // 隐藏价格线
        priceLineVisible: false,
        // 隐藏指示点
        crosshairMarkerVisible: false,
      });

      if (props.content && props.content.length > 0) {
        lineSeries.setData(props.content);
        chartLineSeries.timeScale().fitContent();
      }
    } catch (error) {
      console.error('Chart initialization error:', error);
    }
  }, 100);
}

// 处理窗口大小变化
const handleResize = () => {
  const container = document.querySelector('.' + props.containerLineSeries);
  if (chartLineSeries && container) {
    const width = container.clientWidth || 200;
    const height = container.clientHeight || 100;
    
    chartLineSeries.applyOptions({
      width: width,
      height: height
    });
    
    if (lineSeries && props.content && props.content.length > 0) {
      chartLineSeries.timeScale().fitContent();
    }
  }
};

onMounted(() => {
  // 延迟初始化确保DOM完全渲染
  setTimeout(() => {
    initSeries();
    
    // 添加 resize 事件监听
    window.addEventListener('resize', handleResize);
    
    // 使用 ResizeObserver 监听容器尺寸变化 (如果支持)
    if (window.ResizeObserver) {
      const container = document.querySelector('.' + props.containerLineSeries);
      if (container) {
        resizeObserver = new ResizeObserver(handleResize);
        resizeObserver.observe(container);
      }
    }
  }, 200);
});

onUnmounted(() => {
  // 清理事件监听
  window.removeEventListener('resize', handleResize);
  
  // 清理 ResizeObserver
  if (resizeObserver) {
    resizeObserver.disconnect();
  }
  
  // 销毁图表
  if (chartLineSeries) {
    chartLineSeries.remove();
  }
});

watch(
  () => props.content,
  (newContent) => {
    if (!chartLineSeries) return;
    if (!lineSeries) {
      lineSeries = chartLineSeries.addSeries(new LineSeries({ color: props.lineColor }));
    }

    if (newContent && newContent.length > 0) {
      lineSeries.setData(newContent);
      chartLineSeries.timeScale().fitContent();
    }
  },
  { immediate: true, deep: false }
);

watch(
  () => props.lineColor,
  (newColor) => {
    if (!newColor || !chartLineSeries || !lineSeries) return;

    // 更新线条颜色
    lineSeries.applyOptions({
      color: newColor
    });
  },
  { immediate: true }
);

</script>

<style scoped>
/* 确保容器有最小尺寸 */
.line-series-container {
  min-width: 50px;
  min-height: 30px;
}
/* 隐藏lightweight-charts的图标链接 */
:deep(.product-chart table tr a) {
  display: none !important;
}

/* 通用隐藏所有表格中的链接 */
:deep(table tr a) {
  display: none !important;
}
</style>